package com.novoda.runbuddy.activity.stopwatch;

//NOTE: This class is not currently used.  It will be removed from the project once I am sure we don't need it anymore.  - JJM

import java.util.Calendar;

import android.os.Handler;
import android.os.Message;
import android.pim.DateFormat;

import com.novoda.runbuddy.model.StopwatchPoJo;
import com.novoda.runbuddy.provider.ActivityID;

public class StopwatchThread implements Runnable {

	private Thread			thread		= null;
	private boolean			stopped		= true;
	private long			startTime	= 0;
	private long			endTime		= 0;
	private Handler			stopClockServiceHandler;
	protected Calendar		calendar;
	private StopwatchPoJo	stopClock;

	public StopwatchThread(Handler stopClockServiceHandler) {
		this.stopClockServiceHandler = stopClockServiceHandler;
	}

	public void run() {

		this.calendar = Calendar.getInstance();
		startTime = System.currentTimeMillis();

		while (!stopped) {
			sendMessageEvery100millisecs();
		}

		endTime = System.currentTimeMillis();
	}

	private void sendMessageEvery100millisecs() {
		Message message;
		message = new Message();
		message.what = ActivityID.UPDATESTOPCLOCK;
		stopClockServiceHandler.sendMessage(message);

		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}

	public void start() {
		if (thread != null && thread.isAlive()) {
			return;
		}
		stopped = false;
		thread = new Thread(this, "rbuddy_stopwatch");
		thread.start();
		stopClock = new StopwatchPoJo();

	}

	public synchronized void stop() {
		stopped = true;
		stopClock.stop();
		notifyAll();
	}

	public synchronized String getElapsedTime() {

		Long elapsedTime = (System.currentTimeMillis() - this.startTime);

		calendar.setTimeInMillis(elapsedTime);
		String hours = "00";
		String minutes = DateFormat.format("mm", calendar).toString();
		String seconds = DateFormat.format("ss", calendar).toString();
		String ms = getLastMilliseconds(elapsedTime);

		return hours + ":" + minutes + ":" + seconds + "." + ms;

	}

	public synchronized long getStartTime() {
		return startTime;
	}

	public synchronized long getEndTime() {
		try {
			while (thread.isAlive()) {
				// 100 supposedly looks odd
				wait(200);
			}
		} catch (InterruptedException ignored) {
			// ignored
		}
		return endTime;
	}

	public synchronized String getLastMilliseconds(Long milliseconds) {
		int lengthOfTimeString = milliseconds.toString().length();

		if (lengthOfTimeString > 1) { // Is this even correct?
			String lastSecondsInMilliseconds = milliseconds.toString().substring(lengthOfTimeString - 2);
			return lastSecondsInMilliseconds;
		} else {
			return "00";
		}

	}

	public synchronized long getDuration() {
		return getEndTime() - startTime;
	}

	public StopwatchPoJo getStopClock() {
		return stopClock;
	}

}